'use strict';

const RouterService = require('../base');
const { Op } = require('sequelize');
const {CommonDeletedEnum} = require("../../utils/enum");
class DistributionService extends RouterService {
    static get modelName() {
        return 'Business.Distribution';
    }
    getPageInclude() {
        return [
            {
                model: this.ctx.model.Business.User,
                as: 'user'
            }
        ]
    }
    async beforeCreate(data) {
        // 查询是否重复 user_id user_type时
        const distribution = await this.ctx.model.Business.Distribution.findOne({
            where: {
                user_id: data.user_id,
                user_type: data.user_type,
                deleted: CommonDeletedEnum.NOT_DELETED
            }
        });
        if (distribution) {
            throw new Error('已存在');
        }
        return true
    }
    async beforeUpdate(id, data) {
        // 查询是否重复 user_id user_type时并且ID不等于自己的
        const distribution = await this.ctx.model.Business.Distribution.findOne({
            where: {
                user_id: data.user_id,
                user_type: data.user_type,
                id: {
                    [Op.ne]: id
                },
                deleted: CommonDeletedEnum.NOT_DELETED
            }
        });
        if (distribution) {
            throw new Error('已存在');
        }
        return true
    }
}

module.exports = DistributionService;
